import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { execSync } from 'child_process';

// 在ES模块中模拟__dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 定义目录路径
const distDir = path.resolve(__dirname, '../dist');
const backupDir = path.resolve(__dirname, '../dist-backup');

// 复制目录的函数
function copyDir(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const files = fs.readdirSync(src);
  
  for (const file of files) {
    const srcPath = path.join(src, file);
    const destPath = path.join(dest, file);
    
    if (fs.lstatSync(srcPath).isDirectory()) {
      copyDir(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

// 删除目录的函数
function deleteDir(dir) {
  if (fs.existsSync(dir)) {
    fs.rmdirSync(dir, { recursive: true });
  }
}

// 备份现有文件
if (fs.existsSync(distDir)) {
  console.log('备份现有dist文件...');
  deleteDir(backupDir);
  copyDir(distDir, backupDir);
}

// 执行构建命令
console.log('开始构建...');
execSync('vue-cli-service build', { stdio: 'inherit' });

// 恢复非覆盖文件
if (fs.existsSync(backupDir)) {
  console.log('恢复非覆盖文件...');
  copyDir(backupDir, distDir);
  deleteDir(backupDir);
}

console.log('构建完成');